<?php


namespace App\Services;

use alipay\aop\AopClient;
use antcloud\YiDunSdk\YidunRiskClient;
use App\Exceptions\ApiErrorException;
use App\Models\AppTypeModel;
use App\Models\MemberAlipayRiskCredit;
use App\Models\Order;
use App\Models\UserIdcardInfo;
use Illuminate\Support\Facades\Log;

class AlipayService extends AlipayBaseService
{

    /**
     * 图片上传阿里云oss
     */
    public static function upload($fileObj, $filePath)
    {
        $ossClient = new \OSS\OssClient(
            config('alipay.oss.accessKeyId'),
            config('alipay.oss.accessKeySecret'),
            config('alipay.oss.endpoint')
        );
        $res = $ossClient->uploadFile(config('alipay.oss.bucket'), $fileObj, $filePath);
        if ($res) {
            return ['status' => true, 'data' => $fileObj, 'message' => '上传成功', 'info' => $res];
        }
        return ['status' => false, 'message' => '上传失败', 'info' => ''];
    }

    /**
     * 上传阿里云oss
     * @param bool $sizeLimit
     * @param bool $riginalName
     * @return array
     * @throws \OSS\Core\OssException
     */
    public static function uploadFile($sizeLimit = true, $riginalName = false)
    {
        Log::info('上传图片' . json_encode($_FILES));
        $file = isset($_FILES['file']) ? $_FILES['file'] : [];
        if ($file && $file['error'] == 0) {
            if ($sizeLimit) {
                if ($file['size'] >= 2 * 1024 * 1024) {
                    return ['status' => false, 'message' => '上传图片过大'];
                }
            }
            $imgtype = explode('/', $file['type']);
            $object = $riginalName ? $file['name'] : createNo() . '.' . $imgtype[1];
            $ossClient = new \OSS\OssClient(config('alipay.oss.accessKeyId'), config('alipay.oss.accessKeySecret'), config('alipay.oss.endpoint'));
            $res = $ossClient->uploadFile(config('alipay.oss.bucket'), $object, $file['tmp_name']);
            if ($res) {
                return ['status' => true, 'data' => $object, 'message' => '上传成功'];
            }
        }
        return ['status' => false, 'message' => '上传失败'];
    }


    /**
     *
     * 授权协议oss参数
     * endpoint:   oss-cn-shanghai.aliyuncs.com;
     * accessKeyId =   LTAI5tDxRxZMvxEYmeU6S3eh;
     * accessKeySecret =   WKxTWk8SgI3zNGD07urQY1NDTYavnO;
     * bucketName =   shouwei;
     * objectName = 必须以 "approve_files/" 开头
     * @param $fileObj
     * @param $filePath
     * @return array
     * @throws \OSS\Core\OssException
     *
     */
    public static function boolUpload($fileObj, $filePath)
    {
        $ossClient = new \OSS\OssClient('LTAI5tDxRxZMvxEYmeU6S3eh', 'WKxTWk8SgI3zNGD07urQY1NDTYavnO', 'oss-cn-shanghai.aliyuncs.com');
        $res = $ossClient->uploadFile('shouwei', 'approve_files/' . $fileObj, $filePath);
        if ($res) {
            return ['status' => true, 'data' => $fileObj, 'message' => '上传成功'];
        }
        return ['status' => false, 'message' => '上传失败'];
    }

    /**
     * 订单中心
     * @param $orderData
     * @return array
     * @throws \Exception
     */
//     public static function orderSyncUpload($orderData)
//     {
//         $flag = false;
//         if (
//             !isset($orderData['orderGoodsImg']) || empty($orderData['orderGoodsImg']) &&
//             !isset($orderData['goodsName']) || empty($orderData['goodsName']) &&
//             !isset($orderData['orderPrimaryId']) || empty($orderData['orderPrimaryId']) &&
//             !isset($orderData['orderId']) || empty($orderData['orderId']) &&
//             !isset($orderData['zmUserId']) || empty($orderData['zmUserId']) &&
//             !isset($orderData['orderPrice']) || empty($orderData['orderPrice']) &&
// //            !isset($orderData['leaseTerm']) || empty($orderData['leaseTerm']) &&
//             !isset($orderData['orderRentPrice']) || empty($orderData['orderRentPrice']) &&
//             !isset($orderData['outTradeNo']) || empty($orderData['outTradeNo']) &&
//             !isset($orderData['tradeNo']) || empty($orderData['tradeNo'])
//         ) {
//             return ['status' => $flag, 'message' => '参数错误'];
//         }
//         self::requestLog('订单中心订单数据入参', $orderData);
//         $file_url = $orderData['orderGoodsImg'];
//         $file = file_get_contents($file_url);
//         $file_name = dirname(dirname(dirname(__FILE__))) . '/storage/tmp/' . md5($file_url) . '.png';
//         file_put_contents($file_name, $file);
//         $alipayFileImgrequest = new \AlipayMerchantItemFileUploadRequest();
//         $alipayFileImgrequest->setScene("SYNC_ORDER");
//         $alipayFileImgrequest->setFileContent("@" . $file_name);
//         $fileResult = self::aliPayXxzRequest()->execute($alipayFileImgrequest);
//         self::requestLog('订单中心上传商品图片', $alipayFileImgrequest, $fileResult);
//         $fileRes = self::methodFormat($alipayFileImgrequest, $fileResult);
//         if ($fileRes['status'] && $fileRes['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
//             $material_id = $fileRes['data']['material_id'];
//             $orderRequest = new \AlipayMerchantOrderSyncRequest();
//             $orderParams = [
//                 'out_biz_no' => isset($orderData['leaseTerm']) ? $orderData['outTradeNo'] : $orderData['orderId'],
//                 'buyer_id' => $orderData['zmUserId'],
//                 'amount' => $orderData['orderRentPrice'],
//                 'trade_no' => $orderData['tradeNo'],
//                 'item_order_list' => [
//                     'item_name' => isset($orderData['leaseTerm']) ? $orderData['goodsName'] . '-第' . $orderData['leaseTerm'] . '期' : $orderData['goodsName'],
//                     'unit_price' => $orderData['orderPrice'],
//                     'quantity' => '1',
//                     'ext_info' => [
//                         'ext_key' => 'image_material_id',
//                         'ext_value' => $material_id
//                     ]
//                 ],
//                 'ext_info' => [
//                     [
//                         'ext_key' => 'tiny_app_id',
//                         'ext_value' => config('alipay.xxz_appId')//appID
//                     ],
//                     [
//                         'ext_key' => 'merchant_order_status',
//                         'ext_value' => 'MERCHANT_CONFIRMED'
//                     ],
//                     [
//                         'ext_key' => 'merchant_order_link_page',
//                         'ext_value' => 'pages/user/orderpay/orderpay?id=' . $orderData['orderPrimaryId']
//                     ]
//                 ]
//             ];
//             $orderRequest->setBizContent(json_encode($orderParams));
//             $orderResult = self::aliPayXxzRequest()->execute($orderRequest);
//             self::requestLog('订单中心创建订单', $orderParams, $orderResult);
//             $orderRes = self::methodFormat($orderRequest, $orderResult);
//             if ($orderRes['status'] && $orderRes['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
//                 // 成功
//                 if (file_exists($file_name)) {
//                     unlink($file_name);
//                 }
//                 $flag = true;
//             }
//             self::addLog($orderData['orderId'], $orderParams, $orderResult, self::LOG_TYPE_ORDER_INFO, $flag);
//         }
//
//         return ['status' => $flag, 'message' => $flag ? '成功' : '失败'];
//     }

    /**
     * 模板消息
     * @param $param
     * @return array
     * @throws \Exception
     */
    // public static function templateMessageSend($param)
    // {
    //     $flag = false;
    //     $templateRequest = new \AlipayOpenAppMiniTemplatemessageSendRequest();
    //     $templateRequest->setBizContent(json_encode($param));
    //     $templateResult = self::aliPayXxzRequest()->execute($templateRequest);
    //     self::requestLog('模板消息', $param, $templateResult);
    //     $templateRes = self::methodFormat($templateRequest, $templateResult);
    //     if ($templateRes['status'] && $templateRes['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
    //         // 成功
    //         $flag = true;
    //     }
    //     return ['status' => $flag, 'message' => $flag ? '发送成功' : '发送失败'];
    // }

    /**
     * 登录授权 通过authcode获取authtoken
     * @param $authCode
     * @param string $type
     * @return array
     * @throws \Exception
     */
    public static function authToken($miniId, $authCode, $type = 'web', $header = [])
    {
        $flag = false;
        $alipayAccessTokenRequest = new \AlipaySystemOauthTokenRequest();
        $alipayAccessTokenRequest->setGrantType("authorization_code");
        $alipayAccessTokenRequest->setCode($authCode);
        if ($type == 'web') {
            $result = self::aliPayRequest()->execute($alipayAccessTokenRequest);
            self::requestLog('网页授权登录获取access_token', $alipayAccessTokenRequest, $result);
        } else {
            $result = self::aliPayXxzRequest($miniId)->execute($alipayAccessTokenRequest);
            self::requestLog('小程序授权获取access_token', $alipayAccessTokenRequest, $result);
        }
        $accessTokenData = self::methodFormat($alipayAccessTokenRequest, $result);
        if ($accessTokenData['status'] && isset($accessTokenData['data']['access_token'])) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $accessTokenData['data'] : $accessTokenData];
    }

    /**
     * 登录授权 $accessToken获取用户信息
     * @param $accessToken
     * @param string $type
     * @return array
     * @throws \Exception
     */
    public static function userInfo($miniId, $accessToken, $type = 'web')
    {
        $flag = false;
        $alipayUserInfoRequest = new \AlipayUserInfoShareRequest ();

        if ($type == 'web') {
            $result = AlipayService::aliPayRequest()->execute($alipayUserInfoRequest, $accessToken);
            self::requestLog('网页授权登录获取userInfo', ['accessToken' => $accessToken], $result);
        } else {
            $result = AlipayService::aliPayXxzRequest($miniId)->execute($alipayUserInfoRequest, $accessToken);
            self::requestLog('小程序授权登录获取userInfo', ['accessToken' => $accessToken], $result);
        }
        $userInfoData = AlipayService::methodFormat($alipayUserInfoRequest, $result);
        if ($userInfoData['status'] && $userInfoData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        self::requestLog('accessToken获取用户信息', $miniId, $result);

        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $userInfoData['data'] : $userInfoData];
    }

    /**
     * 芝麻信用订单履约
     * status参数 默认 COMPLETE同步用户已履约 ，CLOSED同步履约已取消，VIOLATED用户已违约
     * @param $orderData
     * @return array
     * @throws \Exception
     */
    public static function orderInfo($miniId, $orderData)
    {
        $flag = false;
        if (
            !isset($orderData['orderId']) || empty($orderData['orderId']) &&
            !isset($orderData['outTradeNo']) || empty($orderData['outTradeNo']) &&
            !isset($orderData['tradeNo']) || empty($orderData['tradeNo'])
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $orderData['status'] = isset($orderData['status']) ? $orderData['status'] : 'COMPLETE';
        if (!in_array($orderData['status'], ['COMPLETE', 'CLOSED', 'VIOLATED'])) {
            return ['status' => $flag, 'message' => '状态错误'];
        }
        $alipayOrderInfoRequest = new \AlipayTradeOrderinfoSyncRequest();
        $data['trade_no'] = $orderData['tradeNo'];
        $data['out_request_no'] = $orderData['outTradeNo'];
        $data['biz_type'] = 'CREDIT_AUTH';
        $data['order_biz_info'] = json_encode(['status' => $orderData['status']]);
        $alipayOrderInfoRequest->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($alipayOrderInfoRequest);
        self::requestLog('芝麻信用订单履约数据', $orderData, $result);
        $orderInfoData = AlipayService::methodFormat($alipayOrderInfoRequest, $result);
        if ($orderInfoData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        self::addLog($orderData['orderId'], $data, $result, self::LOG_TYPE_ORDER_ZM, $flag);
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $orderInfoData['data'] : $orderInfoData];
    }

    /**
     * 生成二维码
     * @param  $goods_id
     * @return array
     * @throws \Exception
     */
    /*
   public static function createQrCode($goods_id, $goods_name)
   {
       $flag = false;
       $alipayOpenAppQrcodeCreateRequest = new \AlipayOpenAppQrcodeCreateRequest();
       $data = [
           'url_param' => 'pagesA/pages/productDetails/productDetails',
           'query_param' => 'goodsId=' . $goods_id . '&from=qrcode',
           'describe' => $goods_name
       ];
       $alipayOpenAppQrcodeCreateRequest->setBizContent(json_encode($data));
       $result = self::aliPayXxzRequest()->execute($alipayOpenAppQrcodeCreateRequest);
       self::requestLog('商品分享生成二维码', $data, $result);
       $resData = AlipayService::methodFormat($alipayOpenAppQrcodeCreateRequest, $result);
       if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
           // 成功
           $flag = true;
       }
       return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
   }
   */
    public static function createQrCode($miniId, $goods_id, $goods_name, $sale_user_id = '', $qrcode = 'qrcode')
    {
        $flag = false;
        $alipayOpenAppQrcodeCreateRequest = new \AlipayOpenAppQrcodeCreateRequest();
        $data = [
            'url_param' => 'pagesA/pages/productDetails/productDetails',
            'query_param' => 'goodsId=' . $goods_id . '&saleuserid=' . $sale_user_id . '&from=' . $qrcode,
            'describe' => $goods_name
        ];
        // if(!empty($sale_user_id)){
        //     $data['query_param'] = 'goodsId='.$goods_id.'&sale_user_id='.$sale_user_id.'&from=qrcode';
        // }
        // $data['query_param'] = urlencode($data['query_param']);

        $alipayOpenAppQrcodeCreateRequest->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($alipayOpenAppQrcodeCreateRequest);
        self::requestLog('商品分享生成二维码', $data, $result);
        $resData = AlipayService::methodFormat($alipayOpenAppQrcodeCreateRequest, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    /**
     * 生成店铺二维码
     * @param  $member_id
     * @param  $shopname
     * @return array
     * @throws \Exception
     */
    public static function shopQrCode($member_id, $shopname)
    {
        $flag = false;
        $alipayOpenAppQrcodeCreateRequest = new \AlipayOpenAppQrcodeCreateRequest();
        $data = [
            'url_param' => 'pages/storeDetails/storeDetails',
            'query_param' => 'memberId=' . $member_id . '&from=qrcode&shopname=' . $shopname,
            'describe' => $shopname
        ];
        $alipayOpenAppQrcodeCreateRequest->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest()->execute($alipayOpenAppQrcodeCreateRequest);
        self::requestLog('店铺生成二维码', $data, $result);
        $resData = AlipayService::methodFormat($alipayOpenAppQrcodeCreateRequest, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : []];
    }

    // /**
    //  * 可信实人认证
    //  * @param $params
    //  * @return array
    //  * @throws \Exception
    //  */
    // public static function alipayFaceauth($params)
    // {
    //     $flag = false;
    //     if (
    //         !isset($params['requestNo']) || empty($params['requestNo']) &&
    //         !isset($params['certName']) || empty($params['certName']) &&
    //         !isset($params['certNo']) || empty($params['certNo']) &&
    //         !isset($params['returnUrl']) || empty($params['returnUrl'])
    //     ) {
    //         return ['status' => $flag, 'message' => '参数错误'];
    //     }
    //     $request = [
    //         "biz_code" => "FACE",
    //         "cert_name" => $params['certName'],
    //         "cert_no" => $params['certNo'],
    //         "cert_type" => "IDENTITY_CARD",
    //         "identity_type" => "CERT_INFO",
    //         "outer_order_no" => $params['requestNo'],
    //         "scene_id" => config('alipay.antchain.facevrf.scene_id'),
    //         "method" => "di.realperson.facevrf.server.create",
    //         "version" => "1.0",
    //         "product_instance_id" => "REALPERSON-PROD",
    //         "region_name" => "CN-HANGZHOU-FINANCE",
    //         "return_url" => $params['returnUrl']
    //     ];
    //     $result = self::getAntCloudClient()->execute($request);
    //     self::requestLog('实人认证数据', $request, $result);
    //     if ($result['result_code'] == 'OK') {
    //         $flag = true;
    //     }
    //     return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $result];
    // }

    // /**
    //  * 可信实人认证结果查询
    //  * @param $params
    //  * @return array
    //  * @throws \Exception
    //  */
    // public static function alipayFaceauthInfo($params)
    // {
    //     $flag = false;
    //     if (
    //         !isset($params['certifyId']) || empty($params['certifyId'])
    //     ) {
    //         return ['status' => $flag, 'message' => '参数错误'];
    //     }
    //     $request = [
    //         "biz_code" => "FACE",
    //         "certify_id" => $params['certifyId'],
    //         "outer_order_no" => config('alipay.alipayUID'),
    //         "cert_type" => "IDENTITY_CARD",
    //         "identity_type" => "CERT_INFO",
    //         "scene_id" => config('alipay.antchain.facevrf.scene_id'),
    //         "method" => "di.realperson.facevrf.server.query",
    //         "version" => "1.0",
    //         "product_instance_id" => "REALPERSON-PROD",
    //         "region_name" => "CN-HANGZHOU-FINANCE",
    //     ];
    //     $result = self::getAntCloudClient()->execute($request);
    //     self::requestLog('实人认证结果查询', $request, $result);
    //     if ($result['result_code'] == 'OK') {
    //         $flag = true;
    //     }
    //     return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $result];
    // }

    // /**
    //  * 支付宝实人认证
    //  * @param $params
    //  * @return array
    //  */
    // public static function alipayUserAuth($params)
    // {
    //     $flag = false;
    //     $res_data = [];
    //     if (
    //         !isset($params['requestNo']) || empty($params['requestNo']) &&
    //         !isset($params['certName']) || empty($params['certName']) &&
    //         !isset($params['certNo']) || empty($params['certNo']) &&
    //         !isset($params['returnUrl']) || empty($params['returnUrl'])
    //     ) {
    //         return ['status' => $flag, 'message' => '参数错误'];
    //     }
    //     $data = [
    //         "biz_code" => "FACE",
    //         "outer_order_no" => $params['requestNo'],
    //         "identity_param" => [
    //             "identity_type" => "CERT_INFO",
    //             "cert_type" => "IDENTITY_CARD",
    //             "cert_name" => $params['certName'],
    //             "cert_no" => $params['certNo'],
    //         ],
    //         "merchant_config" => ["return_url" => $params['returnUrl']]
    //     ];
    //     $request = new \AlipayUserCertifyOpenInitializeRequest();
    //     $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
    //     $result = self::aliPayXxzRequest()->execute($request);
    //     self::requestLog('支付宝实人认证初始化', $data, $result);
    //     $resData = AlipayService::methodFormat($request, $result);
    //     if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
    //         if ($resData['data']['certify_id']) {
    //             $certify_id = $resData['data']['certify_id'];
    //             $request1 = new \AlipayUserCertifyOpenCertifyRequest($certify_id);
    //             $request1->setBizContent(json_encode(['certify_id' => $certify_id]));
    //             $certify_url = self::aliPayXxzRequest()->pageExecute($request1, "GET");
    //             self::requestLog('支付宝实人认证开始认证', ['certify_id' => $certify_id], $certify_url);
    //             if ($certify_url) {
    //                 $res_data['certify_id'] = $certify_id;
    //                 $res_data['certify_url'] = $certify_url;
    //                 $flag = true;
    //             }
    //         }
    //     }
    //     return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $res_data : []];
    // }


    // /**
    //  * 支付宝实人认证查询
    //  * @param $params
    //  * @return array
    //  */
    // public static function alipayAuthCheck($certify_id)
    // {
    //     $flag = false;
    //     if (!$certify_id) {
    //         return ['status' => $flag, 'message' => '参数错误'];
    //     }
    //     $request = new \AlipayUserCertifyOpenQueryRequest();
    //     $request->setBizContent(json_encode(['certify_id' => $certify_id]));
    //     $result = self::aliPayXxzRequest()->execute($request);
    //     $resData = AlipayService::methodFormat($request, $result);
    //     self::requestLog('支付宝实人认证开始认证', ['certify_id' => $certify_id], $resData);
    //     if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
    //         // 成功
    //         $flag = true;
    //     }
    //     return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : []];
    // }


    /**
     * 支付宝手机号解析
     * @param $params
     * @return array
     */
    public static function alipayMobileAnalysis($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['mobileStr']) || empty($params['mobileStr'])
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $appType = AppTypeModel::findById($miniId);
        $ret = openssl_decrypt($params['mobileStr'], 'AES-128-CBC', base64_decode($appType['decrypt_key']), 0);
        $result = json_decode($ret, true);
        if ($result && $result['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            $flag = true;
        }
        self::requestLog('支付宝手机号码解析', $params, $result);
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $result];
    }

    // public static function alipayIDNumberAnalysis($params)
    // {
    //     $flag = false;
    //     if (
    //         !isset($params['mobileStr']) || empty($params['mobileStr'])
    //     ) {
    //         return ['status' => $flag, 'message' => '参数错误'];
    //     }
    //     $ret = openssl_decrypt($params['mobileStr'], 'AES-128-CBC', base64_decode(config('alipay.xxz_decrypt')), 0);
    //     $result = json_decode($ret, true);
    //     if ($result && $result['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
    //         $flag = true;
    //     }
    //     self::requestLog('支付宝身份信息解析', $params, $result);
    //     return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $result];
    // }

    /**
     * 唤起资金预授权
     *
     * @param $miniId
     * @param $params
     * @return array
     */
    public static function alipayPreLicensing($miniId, $params)
    {
        $appConfig = AppTypeModel::findById($miniId);

        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&// 订单编号
            !isset($params['goodsTitle']) || empty($params['goodsTitle']) &&// 商品标题
            !isset($params['preAmount']) || empty($params['preAmount']) &&// 冻结总金额
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) &&// 回调地址
            !isset($params['zmCategory']) || empty($params['zmCategory'])// 芝麻信用免押分类
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $foregift = sprintf("%01.2f", $params['preAmount'] * 0.205); // 冻结总金额的20.5%
        $data = [
            'out_order_no' => $params['orderNo'] . "|" . time(),
            'out_request_no' => $params['orderNo'] . mt_rand(9999, 99999),
            'amount' => $params['preAmount'],
            'payee_user_id' => $appConfig->alipay_uid,
            'order_title' => mb_substr(isset($params['goodsTitle']) ? $params['goodsTitle'] : '预授权冻结完成', 0, 100),
            'product_code' => 'PRE_AUTH_ONLINE',// PRE_AUTH_ONLINE//PREAUTH_PAY
            'deposit_product_mode' => 'POSTPAY_UNCERTAIN',
            'post_payments' => [['name' => '租金', 'description' => bcdiv($params['preAmount'], isset($params['month_total']) ? $params['month_total'] : 12, 2) . '元/期']],
            'extra_param' => ['category' => $params['zmCategory'], 'serviceId' => config('alipay.zm.credit_id'), "creditExtInfo" => [
                "assessmentAmount" => $params['preAmount'],
                "carrierDesc" => $params['goodsTitle'],
                "rentPeriod" => strval($params['rentPeriod']),
                "rentAmount" => $params['preAmount'],
                "deliveryAddress" => $params['deliveryAddress'],
                "deliveryMobile" => $params['deliveryMobile'],
                "deliveryName" => $params['deliveryName'],
                "riskSchemeId" => '0919v59109185',
            ]
            ],
        ];
        $request = new \AlipayFundAuthOrderAppFreezeRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = self::aliPayXxzRequest($miniId)->sdkExecute($request);
        self::requestLog('唤起资金预授权', $data, $result);
        if ($result) {
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? ['orderStr' => $result] : []];
    }

    /**
     * 预授权转支付
     *
     * @param $miniId
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayPreToPay($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&//订单编号
            !isset($params['leaseId']) || empty($params['leaseId']) &&//租期ID
            !isset($params['authNo']) || empty($params['authNo']) &&//资金预授权单号
            !isset($params['subject']) || empty($params['subject']) &&//订单标题 参考样式财务统一 //'预授权转支付+商品名称+店铺名称';
            !isset($params['totalAmount']) || empty($params['totalAmount']) &&//总金额
            !isset($params['userAlipayUId']) || empty($params['userAlipayUId']) &&//用户支付宝uid
            !isset($params['orderDescribe']) || empty($params['orderDescribe']) &&//订单备注 参考样式财务统一 //'预授权解冻转支付第1期'
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) &&//回调地址
            !isset($params['billingDay']) || empty($params['billingDay'])//账单日时间戳
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        //每15天更换一个号码
        if (($params['billingDay'] + 86400 * 15) > time()) {
            $outTradeNo = $params['orderNo'] . "|" . $params['leaseId'];
        } else {
            $outTradeNo = $params['orderNo'] . "|" . $params['leaseId'] . "|" . floor((time() - $params['billingDay']) / 86400 / 15);
        }
        /*if(in_array($params['leaseId'],self::exceptionHandling())){
            $outTradeNo = $outTradeNo."|0|";
        }*/

        $appConfig = AppTypeModel::findById($miniId);

        $data = [
            'out_trade_no' => $outTradeNo,
            'auth_no' => $params['authNo'],
            'subject' => mb_substr($params['subject'], 0, 255),
            'total_amount' => $params['totalAmount'],
            'buyer_id' => $params['userAlipayUId'],
            'body' => mb_substr($params['orderDescribe'], 0, 128),
            'product_code' => 'PRE_AUTH_ONLINE',
            'seller_id' => $appConfig->alipay_uid,
        ];
        $request = new \AlipayTradePayRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));

        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('预授权转支付', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $resData['data']];
    }

    /**
     * 预授权转支付代扣押金
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function deductDeposit($params)
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&//订单编号
            !isset($params['authNo']) || empty($params['authNo']) &&//资金预授权单号
            !isset($params['subject']) || empty($params['subject']) &&//订单标题 参考样式财务统一 //'预授权转支付+商品名称+店铺名称';
            !isset($params['totalAmount']) || empty($params['totalAmount']) &&//总金额
            !isset($params['userAlipayUId']) || empty($params['userAlipayUId']) &&//用户支付宝uid
            !isset($params['orderDescribe']) || empty($params['orderDescribe']) &&//订单备注 参考样式财务统一 //'预授权解冻转支付第1期'
            !isset($params['notifyUrl']) || empty($params['notifyUrl'])//回调地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $miniId = $params['miniId'];
        $appConfig = AppTypeModel::findById($miniId);

        $outTradeNo = $params['orderNo'] . "|" . time();
        $data = [
            'out_trade_no' => $outTradeNo,
            'auth_no' => $params['authNo'],
            'subject' => mb_substr($params['subject'], 0, 255),
            'total_amount' => $params['totalAmount'],
            'buyer_id' => $params['userAlipayUId'],
            'body' => mb_substr($params['orderDescribe'], 0, 128),
            'product_code' => 'PRE_AUTH_ONLINE',
            'seller_id' => $appConfig->alipay_uid,
        ];
        $request = new \AlipayTradePayRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('预授权转支付代扣押金', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $resData['data']];
    }

    /**
     * 主动支付
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayPrepaymentPay($miniId, $params, $time = '')
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&//订单编号
            !isset($params['leaseId']) || empty($params['leaseId']) &&//租期ID 多期逗号分隔
            !isset($params['subject']) || empty($params['subject']) &&//订单标题 参考样式财务统一 //'主动支付支付+商品名称+店铺名称';
            !isset($params['totalAmount']) || empty($params['totalAmount']) &&//总金额
            !isset($params['userAlipayUId']) || empty($params['userAlipayUId']) &&//用户支付宝uid
            !isset($params['orderDescribe']) || empty($params['orderDescribe']) &&//订单备注 参考样式财务统一 //'主动支付第1，2期'
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) //回调地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $appConfig = AppTypeModel::findById($miniId);
        $orderNo = $params['orderNo'];
        if (!$time) {
            $orderNo = $params['orderNo'] . "|" . time();
        }
        $data = [
            'out_trade_no' => $orderNo,
            'subject' => mb_substr($params['subject'], 0, 255),
            'total_amount' => $params['totalAmount'],
            'buyer_id' => $params['userAlipayUId'],
            'body' => mb_substr($params['orderDescribe'], 0, 128),
            'passback_params' => urlencode($params['leaseId']),
            'product_code' => 'JSAPI_PAY',
            'op_app_id' => $appConfig->app_id,
            'seller_id' => $appConfig->alipay_uid,
        ];
        $request = new \AlipayTradeCreateRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('主动支付唤起收银台', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        // echo '<pre>';
        // print_r($resData);
        // dd(1);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    //PC充值
    public static function alipayPcPay($params)
    {
        $flag = false;
        if (
            !isset($params['out_trade_no']) || empty($params['out_trade_no']) &&//订单编号
            !isset($params['subject']) || empty($params['subject']) &&//标题
            !isset($params['total_amount']) || empty($params['total_amount']) &&//充值金额
            !isset($params['body']) || empty($params['body']) &&
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) &&//回调地址
            !isset($params['returnUrl']) || empty($params['returnUrl'])//同步跳转地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $data = array(
            'out_trade_no' => $params['out_trade_no'],
            'subject' => $params['subject'],
            'total_amount' => $params['total_amount'],
            'body' => $params['body'],
        );
        $request = new \AlipayTradePayRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setReturnUrl($params['returnUrl']);
        $request->setBizContent(json_encode($data));
        $result = self::aliPayRequest()->execute($request);
        self::requestLog('PC充值', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    /**
     * 资金预授权查询
     * @param $miniId
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayPreQuery($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['alipayTradeNo']) || empty($params['alipayTradeNo']) &&// 支付宝的授权资金操作流水号
            !isset($params['authNo']) || empty($params['authNo'])// 资金预授权单号
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $data = [
            'operation_id' => $params['alipayTradeNo'],
            'auth_no' => $params['authNo'],
            'query_options' => ['credit_risk_info']
        ];

        $request = new \AlipayFundAuthOperationDetailQueryRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('预授权查询', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        // dd($resData);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    /**
     * 资金预授权查询芝麻信用风控
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayCreditPreQuery($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['alipay_trade_no']) || empty($params['alipay_trade_no']) &&//支付宝的授权资金操作流水号
            !isset($params['rights_auth_no']) || empty($params['rights_auth_no'])//资金预授权单号
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $data = [
            'operation_id' => $params['alipay_trade_no'],
            'auth_no' => $params['rights_auth_no'],
            'query_options' => ['credit_risk_info']
        ];

        $request = new \AlipayFundAuthOperationDetailQueryRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('预授权查询', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
            $MemberAlipayRiskCredit = new MemberAlipayRiskCredit();

            if ($resData['data']['credit_risk_info']['code'] == 'SUCCESS') {



                $data = json_decode($resData['data']['credit_risk_info']['data'], true);
                $MemberAlipayRiskCredit->insertMember($params['cert_no'], $params['cert_name'], $params['mobile'], $params['uid'],
                    $data['rentOnlineRiskLevelOverall'],
                    $data['rentOnlineRiskLevelMultiRent'],
                    $data['rentOnlineRiskLevelFulfill'],
                    $resData['data']['credit_risk_info']['data']);
            } else {
                $messaage = ['QUERY_REFUSED_FOR_NOT_CREDIT_AUTH' => '非信用预授权，不可查询信用',
                    'QUERY_REFUSED_FOR_ORDER_STATUS' => '当前授权单状态不可查信用',
                    'QUERY_REFUSED_FOR_OPERATION_TYPE' => '当前查询的操作类型不可查信用',
                    'QUERY_REFUSED_FOR_NO_PRIVILEGE' => '没有权限查询异步风控数据',
                    'QUERY_REFUSED_FOR_UNKNOWN_REASON' => '其它未知原因，异步风控数据查询被拒绝',
                    'QUERY_FAILED' => '异步风控数据查询失败',
                ];
                return ['status' => false, 'message' => '获取芝麻信用风控信息失败,' . $messaage[$resData['data']['credit_risk_info']['code']]];
            }


        }

        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    /**
     * 资金预授权解冻
     * @param $params
     * @return array
     * @throws \Exception
     */

    public static function alipayPreThaw($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['amount']) || empty($params['amount']) &&//预授权解冻金额
            !isset($params['authNo']) || empty($params['authNo'])//资金预授权单号
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $data = [
            'out_request_no' => createNo(),
            'amount' => $params['amount'],
            'auth_no' => $params['authNo'],
            'remark' => '订单解冻成功，交易完成',
        ];

        $request = new \AlipayFundAuthOrderUnfreezeRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('预授权解冻', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    /**
     * 支付宝退款详情
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayRefundDetail($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['outTradeNo']) || empty($params['outTradeNo']) &&//商户订单号
            !isset($params['tradeNo']) || empty($params['tradeNo'])//支付宝交易号
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $data = [
            'out_request_no' => $params['out_request_no'],
//            'out_trade_no' => $params['outTradeNo'],
            'trade_no' => $params['tradeNo'],
//            'refund_amount' => $params['amount'],
//            'refund_reason' => '用户取消订单退款',
        ];

        $request = new \AlipayTradeFastpayRefundQueryRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
//        var_dump($result);
        self::requestLog('支付宝退款', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
//        var_dump($resData);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    /**
     * 支付宝退款
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayRefund($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['amount']) || empty($params['amount']) &&//退款金额
            !isset($params['outTradeNo']) || empty($params['outTradeNo']) &&//商户订单号
            !isset($params['tradeNo']) || empty($params['tradeNo'])//支付宝交易号
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $data = [
            'out_trade_no' => $params['outTradeNo'],
            'trade_no' => $params['tradeNo'],
            'out_request_no'=>$params['tradeNo'].time(),
            'refund_amount' => $params['amount'],
            'refund_reason' => '用户取消订单退款',
        ];

        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('支付宝退款', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    public static function alipayRefundCode($params)
    {
        $flag = false;
        if (
            !isset($params['amount']) || empty($params['amount']) &&//退款金额
            !isset($params['outTradeNo']) || empty($params['outTradeNo']) &&//商户订单号
            !isset($params['tradeNo']) || empty($params['tradeNo'])//支付宝交易号
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $data = [
            'out_trade_no' => $params['outTradeNo'],
            'trade_no' => $params['tradeNo'],
            'out_request_no'=>$params['out_request_no'],
            'refund_amount' => $params['amount'],
            'refund_reason' => '用户取消订单退款',
        ];

        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzCertRequest()->execute($request);
        self::requestLog('支付宝退款', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }




    /**
     * 花呗支付
     * @param $params
     * @return array
     * @throws ApiErrorException
     */
    public static function alipayHuabei($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&//订单编号
            !isset($params['goodsTitle']) || empty($params['goodsTitle']) &&//商品标题
            !isset($params['totalAmount']) || empty($params['totalAmount']) &&//总金额
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) &&//回调地址
            !isset($params['buyerId']) || empty($params['buyerId']) && //用户支付宝UID
            !isset($params['huabeiStages']) || empty($params['huabeiStages']) //花呗分期数
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $data = [
            'out_trade_no' => $params['orderNo'] . '|hb' . time(),
            'total_amount' => $params['totalAmount'],
            'buyer_id' => $params['buyerId'],
            'subject' => isset($params['goodsTitle']) ? $params['goodsTitle'] : '花呗支付',
            'extend_params' => ['hb_fq_num' => $params['huabeiStages'], 'hb_fq_seller_percent' => $params['hbFeeBear']],
        ];
        $request = new \AlipayTradeCreateRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('花呗支付', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }


    /**
     * 买断支付
     * @param $params
     * @return array
     * @throws ApiErrorException
     */
    public static function alipayBuyoutPay($params)
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&//订单编号
            !isset($params['subject']) || empty($params['subject']) &&//订单标题 参考样式财务统一 //'主动支付支付+商品名称+店铺名称';
            !isset($params['totalAmount']) || empty($params['totalAmount']) &&//总金额
            !isset($params['userAlipayUId']) || empty($params['userAlipayUId']) &&//用户支付宝uid
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) //回调地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $miniId = $params['miniId'];
        $appConfig = AppTypeModel::findById($miniId);

        $data = [
            'out_trade_no' => $params['orderNo'] . "|" . time(),
            'subject' => mb_substr($params['subject'], 0, 255),
            'total_amount' => $params['totalAmount'],
            'buyer_id' => $params['userAlipayUId'],
            'seller_id' => $appConfig->alipay_uid,
        ];
        $request = new \AlipayTradeCreateRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('买断支付唤起收银台', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }


    /**
     * 支付宝转账 证书转账
     * @param $params
     * @param bool $cert
     * @return array
     * @throws \Exception
     */
    public static function alipayCertTransferAccounts($params)
    {
        // todo whis 2024/12/27 15:45 这个需要固定一个账号去转账
        $flag = false;
        if (
            !isset($params['amount']) || empty($params['amount']) &&//转账金额
            !isset($params['payeeRealName']) || empty($params['payeeRealName']) &&//收款人姓名
            !isset($params['payeeAccount']) || empty($params['payeeAccount']) &&//收款人账号
            !isset($params['remark']) || empty($params['remark'])//转账备注;
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $data = [
            'out_biz_no' => createNo(),
            'trans_amount' => $params['amount'],
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene' => 'DIRECT_TRANSFER',
            'payee_info' => [
                'identity' => $params['payeeAccount'],
                'identity_type' => 'ALIPAY_LOGON_ID',
                'name' => $params['payeeRealName'],
            ],
            'payer_info' => [
                'identity' => config('alipay.alipayUID'),
                'identity_type' => 'ALIPAY_USER_ID',
            ],
            'remark' => mb_substr($params['remark'], 0, 200),
        ];
        $request = new \AlipayFundTransUniTransferRequest();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzCertRequest()->execute($request);
        self::requestLog('支付宝转账', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $resData['data']];
    }



    /**
     * 扫码支付
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayCodeScanningPayment($params)
    {
        // todo whis 2024/12/30 14:44 扫码充值也需要指定一个账号
        $flag = false;
        if (
            !isset($params['outTradeNo']) || empty($params['outTradeNo']) &&//商户流水号 ;
            !isset($params['memberId']) || empty($params['memberId']) &&//商户关联ID ;
            !isset($params['subject']) || empty($params['subject']) &&//订单标题 ;
            !isset($params['orderDescribe']) || empty($params['orderDescribe']) &&//订单描述 ;
            !isset($params['totalAmount']) || empty($params['totalAmount']) &&//总金额
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) //回调地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $data = [
            'out_trade_no' => $params['outTradeNo'],
            'subject' => mb_substr($params['subject'], 0, 255),
            'body' => mb_substr($params['orderDescribe'], 0, 128),
            'total_amount' => $params['totalAmount'],
            'passback_params' => urlencode($params['memberId']),
            'seller_id' => config('alipay.alipayUID'),
            'product_code' => 'FACE_TO_FACE_PAYMENT',
        ];
        $request = new \AlipayTradePrecreateRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest()->execute($request);
        self::requestLog('唤起扫码支付', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }





    /**
     * 个人生成二维码
     * @param  $goods_id
     * @param  $sale_user_id 下单分销商ID
     * @return array
     * @throws \Exception
     */
    public static function createUserQrCode($sale_user_id)
    {
        $flag = false;
        $alipayOpenAppQrcodeCreateRequest = new \AlipayOpenAppQrcodeCreateRequest();
        $data = [
            'url_param' => 'pages/index/index',
            'query_param' => 'saleuserid=' . $sale_user_id . '&from=qrcode',
            'describe' => 'sale'
        ];
        $alipayOpenAppQrcodeCreateRequest->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest()->execute($alipayOpenAppQrcodeCreateRequest);
        self::requestLog('推广分享生成二维码', $data, $result);
        $resData = AlipayService::methodFormat($alipayOpenAppQrcodeCreateRequest, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    public static function createUserShopQrCode($member_id, $shopname)
    {
        $flag = false;
        $alipayOpenAppQrcodeCreateRequest = new \AlipayOpenAppQrcodeCreateRequest();
        $data = [
            'url_param' => 'pagesA/pages/offlineStore/offlineStore',
            'query_param' => 'member_id=' . $member_id . '&shopname=' . $shopname,
            'describe' => 'offlineStore'
        ];
        $alipayOpenAppQrcodeCreateRequest->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest()->execute($alipayOpenAppQrcodeCreateRequest);
        self::requestLog('推广分享生成二维码', $data, $result);
        $resData = AlipayService::methodFormat($alipayOpenAppQrcodeCreateRequest, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }



    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    public static function http_request($url, $post_data, $headers)
    {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => $headers,
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result, true);
    }

    /**
     * 内容风险识别接口服务 - 文本
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function securityRiskText($miniId, $params)
    {
        /*
            app_name数据
            ****app_comment	评论发布/评价发布
            ****app_personal_information	个人资料/昵称文本
            ****app_post	商品名称/商品描述/帖子描述
            ****app_group_chat	群聊文本
            ****app_private_chat	私聊文本
            ****app_text	内容发布
            ****app_article	文章
            ****app_search	搜索
            ****app_recipient_address	收货地址
            ****app_recipient_name	收货人姓名
        */
        $flag = false;
        $request = new \AlipaySecurityRiskContentAnalyzeRequest();
        $reqParams = [
            "app_name" => $params['app_name'],
            "app_scene" => "cs_open_service_text",
            "publish_date" => date('Y-m-d H:i:s'),
            "check_labels" => "politics,porn,illegal,terrorism,abuses,advert",
            "account_id" => config('alipay.xxz_appId'),
            "app_scene_data_id" => date('YmdHis') . mt_rand(1000, 9999) . mt_rand(1000, 9999),
            "text" => $params['content']
        ];
        $request->setBizContent(json_encode($reqParams));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        $result_action = $result->alipay_security_risk_content_analyze_response->result_action;
        if ($result_action == 'PASSED') {
            $flag = true;
        }

        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $result_action];

    }

    /**
     * 内容风险识别接口服务 - 图片
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function securityRiskImg($miniId, $params)
    {
        /*
            app_name数据
            ****app_comment	评论图片/评价图片
            ****app_personal_information	个人资料/头像图片
            ****app_post	社区发布/商品图片
            ****app_group_chat	群聊图片
            ****app_private_chat	私聊图片
            ****app_picture	内容图片
        */
        $flag = false;
        $request = new \AlipaySecurityRiskContentResultGetRequest();
        $reqParams = [
            "app_name" => $params['app_name'],
            "app_scene" => "cs_open_service",
            "publish_date" => date('Y-m-d H:i:s'),
            "check_labels" => "politics,porn,illegal,terrorism,abuses,advert",
            "account_id" => config('alipay.xxz_appId'),
            "app_scene_data_id" => date('YmdHis') . mt_rand(1000, 9999) . mt_rand(1000, 9999),
            "picture_urls" => $params['content'] //http://www.xxx.com/favicon.jpg
        ];
        $request->setBizContent(json_encode($reqParams));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        $result_action = $result->alipay_security_risk_content_result_get_response->result_action;
        if ($result_action == 'PASSED') {
            $flag = true;
        }

        //查询详情结果
        // $request2 = new \AlipaySecurityRiskContentResultGetRequest();
        // $reqParams2 = [
        //         "app_scene_data_id"=>$result->alipay_security_risk_content_result_get_response->app_scene_data_id,
        //         "app_scene"=>'WALLETSNS',
        //         "event_id"=>$result->alipay_security_risk_content_result_get_response->event_id
        //     ];
        // $request2->setBizContent(json_encode($reqParams2));
        // $result2 = self::aliPayXxzRequest()->execute($request2);

        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $result_action];

    }


    /**
     * 扫码支付
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function alipayOrderLeasePay($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['order_id']) || empty($params['totalAmount']) &&//商户流水号 ;
            !isset($params['lease_id'])
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }

        $appConfig = AppTypeModel::findById($miniId);

        $data = [
            'out_trade_no' => $params['order_no'],
            'subject' => '第' . $params['which_period'] . '期部分还款',
            'body' => $params['lease_id'],
            'total_amount' => $params['totalAmount'],
            'seller_id' => $appConfig->alipay_uid,
            'product_code' => 'FACE_TO_FACE_PAYMENT',
            'passback_params' => urlencode($params['lease_id']),
        ];
        $request = new \AlipayTradePrecreateRequest();
        $request->setNotifyUrl(config('alipay.callbackDomain') . '/Supplier/Notice/orderLeasePartialNotify');
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzCertRequest($miniId)->execute($request);
        self::requestLog('唤起扫码支付', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }



    /**
     * 小程序云智能租赁风控查询
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function rentriskQuery($miniId, $params)
    {
        $data = [
            'customer_id' => $params['cert_no'],
            'customer_type' => 'CERT_NO',
            'user_authorization' => '1',
            'source' => 'ALIPAY',
            'out_biz_no' => $params['trade_no'],
            'item_detail' => ['goods_category' => 'RENT_PHONE', 'item_name' => $params['goods_title']],
            'price_detail' => ['period_num' => $params['month_total'], 'deposit_price' => '0', 'initial_rent_price' => $params['rent']],
            'delivery_detail' => ['receiver_name' => $params['realname'], 'receiver_mobile' => $params['mobile'], 'receiver_address' => $params['address']]
        ];
        $request = new \AlipayCloudTraasCloudriskRentriskQueryRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));
        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021004105651180';
        $aop->rsaPrivateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9VEawesbCYBoEm/RDREQ4oA8NmHVnlZKTMDmyePvFlqm9Yhf2wCpR3azcdKXnN0gWuZbAuuWm/MSrHIG6iGv2tvTip79eYPzmz8M2NEz2/bs0egsf7gipxv6WjtDz2alXv2c9zmuc7VZgjR0SYWGhWDCEKhww2clZR5XoXm1WF45WoVuSiuq5i+6YTW0Lm3VzMKQv4v6SEfeWuVwb48qlBihkfkwThIUA9LI0djIvn4NJNC1OQiMLxBPGDqbL+scwSckoIyVplEe6wkLsGlGKIOXe0IhZtC4mR1/jFu/9cVlruqlNu3nCLrx97EtfQLUklumS8l+fqvtr1s0IaTy/AgMBAAECggEAd1Ejc5kMpfcWrozydWoSbHVCx1irtOoog6ZC1l00nqOCuZ2WaKVWhl1j0VOaMos+XUP8491lWcW20/eVMk9DayqGTklVa09IUtXguspfLtFdJ4c6d5b10rlcPNooiWVFOc2gbO0oGK/iXdrQ1YKVmq8PdFtthMPcBu38ZYMM+NGttMX2e3IvC1e2lpV2xkKDjJ7OgU3OAbX0uNJ81xYSFsz42L97B0TCIvWwrSqSH0baJTFByuFVyj5Gpt+TAesY1U3vEpFfZXxtkOsH3qPJn+lTy/IhsHNx7dWA/dW/bfvxEZqEYTZ+dUzNS3HvBO6vQctf122aPJqMZDYD4ceq0QKBgQDog4+FxZRIYul+KxpVcdm3bumOzuclqFbbi77m2RciVDAEHDrbpGXj+7ooH4Qkgpdwa9dfCxGjl0icTyEt1yVRH+6zXHXIJGtIoMQ58UG9psttmJUMMBoc8gPcqP3/96vpshU6e/gXYF+6z3XYihsw0VVAOWqnCJOQxyQWbVNEzQKBgQDQdAcd5v3uwNr64ZPZzkkAZ8HgTwtMMOY/JRpILXJw34z+AO6WKhKO+Q5vVld5OpTAsCTRKZJAodc1It2X44cV/RMSUkzlIWKMAQ8srw5TxnTfOCaAAHaWCXynw3VYeiDtrSczEejfk1ZSsOjaWbETUNkAC7uznjCWcqajd4XnuwKBgHzoiEa+AM3uTS9Zankyg1p2vAPbBPQG/jpNVY3gW/w2K+FZZQkvxQj352a8n5mZik97r6TAZoZytDA8lj9xD/wH4oz6g8+0OOo4a5IRGFcQ7sH+sTtt7+lS3l5Bbsp+vBz8bUkQ5hNw05yg7NcaQkc0fc7VyYTYJ6YkRS/DJXOVAoGBAJJsXi9n+YlDGM7Ps350Q50wROReQa5UTveeBVcb7V5R+YTWfMEobn7VfYlBmhJCzwiG8mWmEOCrjjL5+bPelB4i9cmR3Ae7KrDzcYhOsv6v0ZqWo5yYNrRvl4t0ZbIvn3+0eGuMMgsSQLm3IOl3xUWvLa61jzS9cp3LjTgYFgxPAoGAVcKgVeQNZ0e55FcGwcSOGCUsx0193m9evQN5l4CpUt8jc2hVA7HZLKRHgC0anDfNgUeDTXL2/qFEVElGURuGrQVxgYSw1LAvNUtYEfB9+Pen+jssdbciGwxfD/pcsm6tWDJxiv7Bj4F4U5ZPZForL2iXID1XWbtwDdymX5FmwgE=';
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmeHXe3p2sNhPhH09R1nsEtV1z22c21QRU/8D21Ahojz/pdAJJ9WCw9d2OVeeF4wbkdxeUoMkVcmJhPI5dfcPYWJiQZNOzObU/EpbQCgelANgT3L1FyoDs8IuZXOXFBGXxp7FJUrVL0XPq5fFKrmItdYiPq4HwXFktahK6/ONbQJGZZkubc9J4SjFKMxGWCvyUV/qfaKPwC6N4/2ErDjrfC1KAMjRFWtkYCWb5RJZtvN0yRS+ax5pyJwWJtlCRMc8Q/W00dU+VCeKHie8locGWUyTwJmlMQSUJMUM6YruJF1tSE4gM7mgtMs39514tHd2BjgL4Bpvo39mWy79fbyEwQIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $result = $aop->execute($request);
        self::requestLog('小程序云智能租赁风控查询', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

    public static function AlipayDataBillSellQueryRequest($alipay_order_no)
    {
        $data = [
            'start_time' => date('Y-m-d H:i:s', strtotime('-29 day')),
            'end_time' => date('Y-m-d H:i:s'),
            'alipay_order_no' => $alipay_order_no,
        ];
        $request = new \AlipayDataBillAccountlogQueryRequest ();
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest(10008)->execute($request);
        self::requestLog('账单查询', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        $flag = 0;
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE && isset($resData['data']['detail_list']) && $resData['data']['detail_list']) {
            // 成功
            $flag = $resData['data']['detail_list'];
        }
        return $flag;

    }

    /**
     * 芝麻先享信用服务下单（用户确认场景）
     * @param $params
     * @return array
     */
    public static function creditbizorderCreate($miniId, $params)
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&// 订单编号
            !isset($params['goodsTitle']) || empty($params['goodsTitle']) &&// 商品标题
            !isset($params['rentAmount']) || empty($params['rentAmount']) &&// 冻结总金额
            !isset($params['notifyUrl']) || empty($params['notifyUrl'])// 回调地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $data = [
            'out_order_no' => $params['orderNo'],
            'zm_service_id'=>'2025060500000000000106212300',
            'subject'=>$params['goodsTitle'],
            'order_amount'=>$params['rentAmount'],
            'amount_type'=>'ORDER_AMOUNT',
           'category_id'=> "credit_pay_after_use"

        ];
        $request = new \ZhimaCreditPayafteruseCreditbizorderCreateRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = self::aliPayXxzRequest($miniId)->sdkExecute($request);
        self::requestLog('芝麻先享信用服务下单（用户确认场景）', $data, $result);
        if ($result) {
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? ['orderStr' => $result] : []];
    }


    /**
     * 主动支付
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function creditbizorderCreatePay($miniId, $params, $time = '')
    {
        $flag = false;
        if (
            !isset($params['orderNo']) || empty($params['orderNo']) &&//订单编号
            !isset($params['subject']) || empty($params['subject']) &&//订单标题 参考样式财务统一 //'主动支付支付+商品名称+店铺名称';
            !isset($params['rentAmount']) || empty($params['rentAmount']) &&//总金额
            !isset($params['userAlipayUId']) || empty($params['userAlipayUId']) &&//用户支付宝uid
            !isset($params['notifyUrl']) || empty($params['notifyUrl']) //回调地址
        ) {
            return ['status' => $flag, 'message' => '参数错误'];
        }
        $appConfig = AppTypeModel::findById($miniId);
        $orderNo = $params['orderNo'];
        if (!$time) {
            $orderNo = $params['orderNo'] . "|" . time();
        }
        $data = [
            'out_trade_no' => $orderNo,
            'subject' => mb_substr($params['goodsTitle'], 0, 255),
            'total_amount' => $params['rentAmount'],
            'buyer_id' => $params['userAlipayUId'],
            'body' => '先享后付签约',
            'passback_params' => urlencode($params['leaseId']),
            'product_code' => 'JSAPI_PAY',
            'extend_params'=>[
                'zmServiceId' => '2025060500000000000106212300',
                'creditTradeScene' => 'CREDIT_PAY',
            ],
            'op_app_id' => $appConfig->app_id,
            'seller_id' => $appConfig->alipay_uid,
            'goods_detail' => [
                [
                    'goods_name' => mb_substr($params['goodsTitle'], 0, 128),
                    'goods_category' => 'OTHER',
                    'price' => $params['rentAmount'],
                    'quantity' => 1,
                    'goods_id' => $params['goodsId'],
                ]
            ],
        ];

        $request = new \AlipayTradeCreateRequest();
        $request->setNotifyUrl($params['notifyUrl']);
        $request->setBizContent(json_encode($data));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('主动支付唤起收银台', $data, $result);
        $resData = AlipayService::methodFormat($request, $result);
        // echo '<pre>';
        // print_r($resData);
        // dd(1);
        if ($resData['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
            // 成功
            $flag = true;
        }
        return ['status' => $flag, 'message' => $flag ? '成功' : '失败', 'data' => $flag ? $resData['data'] : $resData];
    }

}
